#include "main.h"

//1.socket   建立套接字文件
//2.connect() 请求连接
//3.read/write  send/recv
//4.shutdown()  

//服务端先接再发
//客户端先发再收
int flg = 0; //私聊标志,置1为私聊

int login()
{
  int rc = 0;
  const char *create = "CREATE TABLE IF NOT EXISTS user(name TEXT NOT NULL UNIQUE,passwd TEXT NOT NULL);";
  char *p2 = 0;
  sqlite3 *db = 0;
  sqlite3_exec(db,create,0,0,&p2);
  if(rc != SQLITE_OK)
  {
    printf("创建表失败\n");
    return -1;
  }
  //printf("创建成功\n");
  //打开数据库
  
  rc = sqlite3_open("user.db",&db);
  if(rc < 0)
  {
    printf("打开数据库失败\n");
    return 0;
  }
  
  int num = 0;
  char sendbuff[256]= "";
  char recvbuff[256]= "";
  int client_socket = socket(AF_INET,SOCK_STREAM,0);
  while (1)
  {

    printf("**************************登录界面**************************\n");
    printf("                  1.注册            2.登录\n");
    scanf("%d",&num);
    if(num == 1)
    {
      //插入数据
      //int insert_data(sqlite3 *db)

      char name[20];
      char passwd[50];

      printf("请输入用户名：\n");
      scanf("%19s",name);
      printf("请输入密码：\n");
      scanf("%49s",passwd);
      strcpy(sendbuff,"@");
      strcat(sendbuff," ");
      strcat(sendbuff,name);
      strcat(sendbuff," ");
      strcat(sendbuff,passwd);
      send(client_socket,sendbuff,strlen(sendbuff),0);//发送到服务器
      recv(client_socket,recvbuff,256,0);


      char insert_str[256];
      snprintf(insert_str,sizeof(insert_str),"INSERT INTO user (name,passwd) VALUES('%s','%s');",name,passwd);
      //const char *insert_str = "INSERT INTO user (name, passwd) VALUES ('mike', 'asd123');";
      char *errmg = NULL;
      if(sqlite3_exec(db,insert_str,NULL,NULL,&errmg) != SQLITE_OK)
      {
        printf("用户名已被注册！请重新输入\n");
        //fprintf(stderr,"SQL error:%s\n",errmg);
        return -1;
      }
      printf("注册成功\n");
      bzero(sendbuff,256);
      bzero(recvbuff,256);
      
    }
    if(num == 2)
    {
      //登录
      //int user_login(sqlite3 *db)

      char login[256];
      char name[20];
      char passwd[50];

      printf("请输入用户名：\n");
      scanf("%19s",name);
      printf("请输入密码：\n");
      scanf("%49s",passwd);
      strcpy(sendbuff,name);
      strcat(sendbuff," ");
      strcat(sendbuff,passwd);
      printf("发送的数据%s\n",sendbuff);
      send(client_socket,sendbuff,strlen(sendbuff),0);//发送到服务器
      recv(client_socket,recvbuff,256,0);
        
      snprintf(login,sizeof(login),"SELECT * FROM user WHERE name = '%s' AND passwd = '%s';",name,passwd);

      sqlite3_stmt *stmt;
      if(sqlite3_prepare_v2(db,login,-1,&stmt,0) != SQLITE_OK)
      {
        return -1;
      }
      int step_result = sqlite3_step(stmt);
      if(step_result == SQLITE_ROW)
      {
        printf("登录成功\n");
        return 0;
      }
      else
      {
        printf("用户名或者密码错误\n");
        return -1;
      }
      bzero(sendbuff,256);
      bzero(recvbuff,256);
    }
  }
}

void display(char chat[][256],char* name)//聊天界面
{

    time_t tm1 = 0;
    char * timstr =NULL;
    tm1 = time(NULL);
    timstr = asctime(localtime(&tm1));
    system("clear");
    //printf("\033[33m\033[31m---------------------------------------------------------\n");
    printf("\033[33m\033[33m--------------------------聊天室-------------------------\n");
    printf("\033[33m\033[31m            %s\n",timstr);
    int k=0;
    for(int i = 0;i<19+k;i++)
    {   
        if(strlen(chat[i])!=0)
        {
            if(strstr(chat[i],"加入了聊天室")!=NULL || strstr(chat[i],"退出了聊天室")!=NULL)
            {
                printf("\033[33m\033[32m%s",chat[i]);
            }
            else if(strstr(chat[i],"悄悄的对你说")!=NULL || strstr(chat[i],"你悄悄的对")!=NULL)
            {
                printf("\033[33m\033[35m%s",chat[i]);
                //k++;
                printf("\n");
            }
            else
            {
                printf("\033[33m\033[37m%s",chat[i]);
            }
        }
        else
            printf("\n");
    }
    printf("\033[33m\033[33m---------------------------------------------------------\n");
    printf("\033[33m\033[31m%s>>:",name);
    fflush(stdout);
    sleep(1);
}



int main(int argc,char ** argv)
{
    if(argc <3 )
    {
        perror("使用: ./client + 服务器IP地址 + 服务器端口号\n");
        return -1;
    }
    int ret = 0;
    //1建立套接字：客户端只有一个套接字。就是cid，把客户端cid与对面的绑定在一起。
    int tcp_client = socket(AF_INET,SOCK_STREAM,0);
    if (tcp_client < 0)
    {
        perror("socket error\n");
        return -1;
    }
    
    //链接服务器，把对面的地址和端口号包装起来
    struct sockaddr_in IPV4;
    memset(&IPV4,0,sizeof(IPV4));
    IPV4.sin_family = AF_INET;
    IPV4.sin_port = htons(atoi(argv[2]));
    IPV4.sin_addr.s_addr = inet_addr(argv[1]);

 
    // 2.建立链接 --- 连接的是主机的，服务器的ip和端口号
    ret = connect(tcp_client,(struct sockaddr * )&IPV4,sizeof(IPV4));
    char buf[128];
    read(tcp_client,buf,sizeof(buf));
    printf("%s\n",buf);
    // if(ret < 0 )
    // {
    //     printf("连接失败..\n");

    // }
    // else
    // {
    //     login();
    //     //select函数  
    //     fd_set rset = {0}; 
    //     struct timeval tm = {0};
    //     int count = 0;
    //     int len = 0;
    //     char recvbuf[256];
    //     char sendbuf[256];
    //     //聊天记录
    //     int i=0, j=0;
    //     char chat[20][256] = {0};
    //     //与对面建立连接以后，就开始发送数据

    //     //输入名字
    //     char name[16] = "";
    //     printf("请输入你在聊天室中的名字：");
    //     scanf("%s",name);
    //     send(tcp_client,name,strlen(name),0);//发送名字到服务器
    
    //     printf("欢迎来到聊天室..\n");
    //     printf("公共场所，请注意您的发言..\n");
    //     sleep(1);

    //     //3.处理聊天数据
    //     while (ret >= 0 )
    //     {
    //         FD_SET(STDIN_FILENO,&rset);
    //         FD_SET(tcp_client,&rset);
    //         tm.tv_sec = 5;
    //         count = select(tcp_client + 1,&rset,NULL,NULL,&tm);
    //         //printf("count : %d\n",count);

    //         /******     收      *******/
    //         if(FD_ISSET(tcp_client,&rset))
    //         {
    //             memset(recvbuf,0,256);
    //             recv(tcp_client,recvbuf,256,0);
    //             if(i<18)
    //             {
    //                 strcpy(chat[i],recvbuf);
    //                 i++;
    //             }
    //             else
    //             {
    //                 for(j = 0;j < 17;j++)
    //                 {
    //                     strcpy(chat[j],chat[j+1]);
    //                 }
    //                 strcpy(chat[j],recvbuf);
    //             }
    //             //printf("%s\n",recvbuf);
    //             display(chat,name);
    //         }

    //         //发送数据   
    //         if(FD_ISSET(STDIN_FILENO,&rset))
    //         {   
    //             memset(sendbuf,0,256);
    //             read(STDIN_FILENO,sendbuf,sizeof(sendbuf));//把数据从外存文件写到内存中
    //             send(tcp_client,sendbuf,strlen(sendbuf),0);
    //             if(strncasecmp(sendbuf,"quit",4) == 0 )
    //             {
    //                 break;
    //             }   
    //         }
    //         if(ret < 0)
    //             break;
    //     }
    //  }
}
